#!/usr/bin/python3
#+
# This script retrieves the Delta-T data from the USNO and outputs it
# in a form that can be included in a Python program.
#
# Copyright 2014 Lawrence D'Oliveiro <ldo@geek-central.gen.nz>.
#
#    This file is part of Pysolar.
#
#    Pysolar is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Pysolar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with Pysolar. If not, see <http://www.gnu.org/licenses/>.
#-

import sys
import re
import urllib.request

if len(sys.argv) == 2 :
    data = open(sys.argv[1], "r").read()
else :
    data = urllib.request.urlopen("ftp://maia.usno.navy.mil/ser7/deltat.data").read().decode("ascii")
#end if

def parse_data(data) :
    for line in data.split("\n") :
        line = line.strip()
        if len(line) != 0 :
            year, month, day, dt = tuple((int, float)[i == 3](s) for i, s in enumerate(re.split(r"\s+", line, 3)))
            yield(year, month, day, dt)
        #end if
    #end for
#end parse_data

entries = parse_data(data)
last_year = None
while True :
    entry = next(entries, None)
    if entry != None :
        year, month, day, dt = entry
        assert day == 1, "not first day of month for year %d, month %d" % (year, month)
    #end if
    if entry == None or year != last_year :
        if last_year != None :
            sys.stdout.write("        ],\n")
            if entry == None :
                sys.stdout.write("    ] # delta_t\n")
            #end if
        #end if
        if entry == None :
            break
        assert last_year == None or last_year + 1 == year, "years not consecutive: %d, %d" % (last_year, year)
        if last_year == None :
            sys.stdout.write("# table generated by util/get_delta_t script\n")
            sys.stdout.write("delta_t_base_year = %d\n" % year)
            sys.stdout.write("delta_t_base_month = %d\n" % month)
            sys.stdout.write("delta_t = \\\n  [\n")
        else :
            assert last_month == 12, "incomplete year %d at month %d" % (last_year, last_month)
        #end if
        sys.stdout.write("        [ # %d\n" % year)
        if last_year != None :
            last_month = 0
        else :
            last_month = None # table might not start in January
        #end if
        last_year = year
    #end if
    assert last_month == None or month == last_month + 1, \
        "months not consecutive for year %d: %d, %d"% (year, last_month, month)
    sys.stdout.write("            %.4f, # %d\n" % (dt, month))
    last_month = month
#end while
